import React, { Component } from 'react';
import {
	base,
	ajax,
	toast,
	createPage,
	getMultiLang} from 'nc-lightapp-front';
const { NCButton, NCDiv, NCTable, NCRadio, NCCheckbox } = base;
import ReportModal from './reportModal/reportModal';
import ReferLoader from '../../../public/ReferLoader/index.js';
import {getTableHeight } from '../pubUtils/method.js';
import { buttonClick, initTemplate } from './events';
import './index.less';
import '../../../public/less/radio.less';
const defaultProps12 = {
	prefixCls: 'bee-table',
	multiSelect: {
		type: 'checkbox',
		param: 'key'
	}
};
class BatchCloseAccount extends Component {
	constructor(props) {
		super(props);
		this.state = {
			pk_orgs: [], //保存所有选中的财务组织
			selectedValue: 'closeAccount', //当前选中的是待结账还是可取消结账
			nccCloseAccountVOs: [], //表格数据
			checkedArray: [], //控制行是否选中
			showReportModal: false, //是否展示结账报告的模态框
			checkedDatas: [], //保存选中的数据
			reportTableData: [], //结账报告表格数据
			json: {}
		};
		this.Defaultcolumns = [];
	}
	componentWillMount() {
		let callback = (json) => {
			this.Defaultcolumns = [
				{
					title: (<div fieldid ="pk_orgName">{json['public-000001']}</div>) /* 国际化处理： 财务组织 */,
					dataIndex: 'pk_orgName',
					key: 'pk_orgName',
					width: 100,
					render: (text) => <div fieldid ="pk_orgName">{text ? text : <span>&nbsp;</span>}</div>
				},
				{
					title: (<div fieldid ="period">{json['public-000002']}</div>) /* 国际化处理： 会计期间 */,
					dataIndex: 'period',
					key: 'period',
					width: 100,
					render: (text) => <div fieldid ="period">{text ? text : <span>&nbsp;</span>}</div>
				},
				{
					title: (<div fieldid ="startDate">{json['public-000003']}</div>) /* 国际化处理： 会计开始时间 */,
					dataIndex: 'startDate',
					key: 'startDate',
					width: 150,
					render: (text) => <div fieldid ="startDate">{text ? text : <span>&nbsp;</span>}</div>
				},
				{
					title: (<div fieldid ="endDate">{json['public-000004'] }</div>)/* 国际化处理： 会计结束时间 */,
					dataIndex: 'endDate',
					key: 'endDate',
					width: 150,
					render: (text) => <div fieldid ="endDate">{text ? text : <span>&nbsp;</span>}</div>
				},
				{
					title: (<div fieldid ="dispReckedOrNot">{json['public-000005']}</div>) /* 国际化处理： 是否结账*/,
					dataIndex: 'dispReckedOrNot',
					key: 'dispReckedOrNot',
					width: 100,
					render: (text) => <div fieldid ="dispReckedOrNot">{text ? text : <span>&nbsp;</span>}</div>
				},
				{
					title: (<div fieldid ="endaccuser">{json['public-000006']}</div>) /* 国际化处理： 结账人*/,
					dataIndex: 'endaccuser',
					key: 'endaccuser',
					width: 150,
					render: (text) => <div fieldid ="endaccuser">{text ? text : <span>&nbsp;</span>}</div>
				},
				{
					title: (<div fieldid ="endacctime">{json['public-000007'] }</div>)/* 国际化处理： 结账时间*/,
					dataIndex: 'endacctime',
					key: 'endacctime',
					width: 150,
					render: (text) => <div fieldid ="endacctime">{text ? text : <span>&nbsp;</span>}</div>
				},
				{
					title: (<div fieldid ="unendaccuser">{json['public-000008']}</div>) /* 国际化处理： 取消结账*/,
					dataIndex: 'unendaccuser',
					key: 'unendaccuser',
					width: 100,
					render: (text) => <div fieldid ="unendaccuser">{text ? text : <span>&nbsp;</span>}</div>
				},
				{
					title: (<div fieldid ="unendacctime">{json['public-000009']}</div>) /* 国际化处理： 取消结账时间*/,
					dataIndex: 'unendacctime',
					key: 'unendacctime',
					width: 100,
					render: (text) => <div fieldid ="unendacctime">{text ? text : <span>&nbsp;</span>}</div>
				}
			];
			this.setState({ json: json }, () => {
				this.handleRadioChange(this.state.selectedValue);
				this.controlButton();
			});
		};
		getMultiLang({ moduleId: 'public', domainName: 'arap', currentLocale: 'simpchn', callback });
	}

	componentWillReceiveProps(nextProps) { }

	getHeadData = () => {
		return (
			<div>
				<p>
					<span>*</span>
					{this.state.json['public-000024']}：
				</p>
				{/* 国际化处理： 财务组织*/}
				<ReferLoader
					fieldid = "FinanceOrgTreeRef"
					tag="test"
					refcode="/uapbd/refer/org/FinanceOrgTreeRef/index.js"
					isMultiSelectedEnabled={true} //是否多选
					isShowUnit={false} //是否跨集团
					isShowDisabledData={false} //是否显示停用
					value={this.state.pk_orgs}
					queryCondition={() => {
						//根据集团过滤财务组织
						return {
							DataPowerOperationCode: 'fi', //使用权组
							isDataPowerEnable: 'Y',
							AppCode: this.props.getSearchParam('c'),
							TreeRefActionExt: 'nccloud.web.refer.sqlbuilder.PrimaryOrgSQLBuilder'
						};
					}}
					onChange={(v) => {
						this.setState({
							pk_orgs: v
						});
					}}
				/>
				<NCRadio.NCRadioGroup
					name="account"
					selectedValue={this.state.selectedValue}
					onChange={this.handleRadioChange.bind(this)}
				>
					<NCRadio value="closeAccount">{this.state.json['public-000025']}</NCRadio>
					{/* 国际化处理： 待结账*/}
					<NCRadio value="cancleCloseAccount">{this.state.json['public-000026']}</NCRadio>
					{/* 国际化处理： 可取消结账*/}
				</NCRadio.NCRadioGroup>
				<NCButton fieldid="query" colors="primary" onClick={this.getTableData.bind(this)}>
					{this.state.json['public-000027']}
					{/* 国际化处理： 查询*/}
				</NCButton>
			</div>
		);
	};

	//控制按钮的可操作性
	controlButton = () => {
		if (this.state.checkedArray.indexOf(true) != -1) {
			this.props.button.setButtonDisabled(['CloseAccount', 'UnCloseAccount'], false);
		} else {
			this.props.button.setButtonDisabled(['CloseAccount', 'UnCloseAccount'], true);
		}
	};

	//单选按钮改变值
	handleRadioChange = (value) => {
		this.setState(
			{ selectedValue: value },
			() => {
				if (value == 'closeAccount') {
					this.props.button.setButtonVisible(['CloseAccount'], true);
					this.props.button.setButtonVisible(['UnCloseAccount'], false);
				} else {
					this.props.button.setButtonVisible(['UnCloseAccount'], true);
					this.props.button.setButtonVisible(['CloseAccount'], false);
				}
			},
			() => {
				this.controlButton();
			}
		);
	};
	//获取表格数据
	getTableData = (type) => {
		let { moudleId, prodId } = this.props;
		let { pk_orgs } = this.state;
		if (pk_orgs.length > 0) {
			let pk_orgId = [];
			let pk_orgNames = [];
			pk_orgs.forEach((val) => {
				pk_orgId.push(val.refpk);
				pk_orgNames.push(val.refname);
			});
			let isCloseAccount = true;
			if (this.state.selectedValue == 'cancleCloseAccount') {
				isCloseAccount = false;
			}
			ajax({
				url: '/nccloud/arap/batchcloseaccount/query.do',
				data: {
					pk_orgs: pk_orgId,
					pk_orgNames: pk_orgNames,
					moudleId: moudleId,
					isCloseAccount: isCloseAccount,
					prodId: prodId
				},
				success: (res) => {
					if (res.data.nccCloseAccountVOs) {
						let datas = res.data.nccCloseAccountVOs;
						if (!type) {
							toast({
								color: 'success',
								content:
									this.state.json['public-000010'] + datas.length + this.state.json['public-000011']
							}); /* 国际化处理： 查询成功,共,条。*/
						}
						let checkedArray = [];
						for (let i = 0; i < datas.length; i++) {
							checkedArray.push(false);
						}
						this.setState(
							{
								nccCloseAccountVOs: datas,
								checkedArray: checkedArray,
								checkedAll: false,
								checkedDatas: [] //清空选中数据
							},
							() => {
								this.controlButton();
							}
						);
					} else {
						if (!type) {
							toast({ color: 'success', content: this.state.json['public-000012'] }); /* 国际化处理： 未查询到数据*/
						}
					}
				}
			});
		} else {
			toast({ color: 'warning', content: this.state.json['public-000013'] }); /* 国际化处理： 请选择财务组织*/
		}
	};

	//点击结账按钮
	handleEndAccount = () => {
		let { checkedArray, nccCloseAccountVOs } = this.state;
		let { sfbz } = this.props;
		let checkedDatas = [];
		let datas = [];
		for (let i = 0; i < checkedArray.length; i++) {
			if (checkedArray[i]) {
				checkedDatas.push(nccCloseAccountVOs[i]);
				datas.push({
					sfbz: sfbz,
					pk_org: nccCloseAccountVOs[i].pk_org_v?nccCloseAccountVOs[i].pk_org_v:nccCloseAccountVOs[i].pk_org,
					period: nccCloseAccountVOs[i].period,
					voCond: {
						m_sPeriodState: 'N', //当月结账状态，肯定为未结账
						pk_periodmonth: nccCloseAccountVOs[i].pk_periodmonth,
						m_sBegDate: nccCloseAccountVOs[i].startDate,
						m_sEndDate: nccCloseAccountVOs[i].endDate
					}
				});
			}
		}
		if (checkedDatas.length > 0) {
			ajax({
				url: '/nccloud/arap/batchcloseaccount/getReport.do',
				data: datas,
				success: (res) => {
					this.setState({
						checkedDatas: checkedDatas,
						reportTableData: res.data
					});
					this.handleOpenOrClose();
				}
			});
		} else {
			toast({ color: 'warning', content: this.state.json['public-000014'] }); /* 国际化处理： 请选中一行数据!*/
			return;
		}
	};

	//点击完成结账动作
	batchCloseAccount = () => {
		let that = this;
		let { moudleId, prodId } = this.props;
		let { reportTableData, checkedDatas } = this.state;
		let trueDatas = []; //结账报告通过可以去结账的财务组织
		let falseDatas = []; //结账报告不通过，不去结账的财务组织
		checkedDatas.map(function (item) {
			if (reportTableData[item.pk_org_v?item.pk_org_v:item.pk_org].state) {
				trueDatas.push({
					pk_org: item.pk_org_v?item.pk_org_v:item.pk_org,
					pk_orgName: item.pk_orgName,
					moudleId: moudleId,
					prodId: prodId,
					period: item.period,
					pk_accperiodmonth: item.pk_accperiodmonth
				});
			} else {
				falseDatas.push({
					pk_orgName: item.pk_orgName,
					message: that.state.json['public-000015'] /* 国际化处理： 结账报告不通过，请查看结账报告。</br>*/
				});
			}
		});
		if (trueDatas.length > 0) {
			ajax({
				url: '/nccloud/arap/batchcloseaccount/batchcloseaccount.do',
				data: trueDatas,
				async: false,
				success: (res) => {
					if (res.data && res.data.length > 0) {
						res.data.map(function (item) {
							falseDatas.push({
								pk_orgName: item.name,
								message: item.message
							});
						});
					}
					this.handleOpenOrClose(); //关闭模态框
					this.getTableData(true); //刷新表格数据
				}
			});
		} else {
			toast({ color: 'warning', content: this.state.json['public-000016'] }); /* 国际化处理： 无可结账项，请查看结账报告。*/
			return;
		}
		if (falseDatas.length > 0) {
			//如果有未结账成功的，展示错误信息
			let error = '';
			falseDatas.map(function (item) {
				error = error + item.pk_orgName + ':' + item.message + ';</br>';
			});
			let message =
				this.state.json['public-000017'] /* 国际化处理： 共结账*/ +
				checkedDatas.length +
				this.state.json['public-000018'] /* 国际化处理： 条，成功*/ +
				(checkedDatas.length - falseDatas.length) +
				this.state.json['public-000019'] /* 国际化处理： 条，失败*/ +
				falseDatas.length +
				this.state.json['public-000020'] /* 国际化处理： 条。</br>失败原因:</br>*/ +
				error;

			toast({
				color: 'danger',
				content: message
			});
		} else {
			toast({ color: 'success', content: this.state.json['public-000021'] }); /* 国际化处理： 全部结账成功*/
		}
	};

	//批量取消结账
	cancelCloseAccount = () => {
		let { moudleId, prodId } = this.props;
		let { checkedArray, checkedDatas, nccCloseAccountVOs } = this.state;
		for (let i = 0; i < checkedArray.length; i++) {
			if (checkedArray[i]) {
				checkedDatas.push(nccCloseAccountVOs[i]);
			}
		}
		if (checkedDatas.length == 0) {
			toast({ color: 'warning', content: this.state.json['public-000014'] }); /* 国际化处理： 请选中一行数据!*/
			return;
		}
		let cancelDatas = [];
		checkedDatas.map(function (item) {
			cancelDatas.push({
				pk_org: item.pk_org_v?item.pk_org_v:item.pk_org,
				pk_orgName: item.pk_orgName,
				moudleId: moudleId,
				prodId: prodId,
				period: item.period,
				pk_accperiodmonth: item.pk_accperiodmonth
			});
		});
		ajax({
			url: '/nccloud/arap/batchcloseaccount/batchcancelcloseaccount.do',
			data: cancelDatas,
			success: (res) => {
				this.getTableData(true); //刷新一次表格数据
				//展现未取消结账成功的错误信息
				let falseDatas = [];
				if (res.data && res.data.length > 0) {
					res.data.map(function (item) {
						falseDatas.push({
							pk_orgName: item.name,
							message: item.message
						});
					});
				}
				if (falseDatas.length > 0) {
					//如果有未取消结账成功的，展示错误信息
					let error = '';
					falseDatas.map(function (item) {
						error = error + item.pk_orgName + ':' + item.message + '。</br>';
					});
					let message =
						this.state.json['public-000022'] /* 国际化处理： 共取消结账*/ +
						checkedDatas.length +
						this.state.json['public-000018'] /* 国际化处理： 条，成功*/ +
						(checkedDatas.length - falseDatas.length) +
						this.state.json['public-000019'] /* 国际化处理： 条，失败*/ +
						falseDatas.length +
						this.state.json['public-000020'] /* 国际化处理： 条。</br>失败原因:</br>*/ +
						error;
					toast({
						duration: 'infinity',
						color: 'warning',
						content: message
					});
				} else {
					toast({ color: 'success', content: this.state.json['public-000023'] }); /* 国际化处理： 全部取消结账成功*/
				}
			}
		});
	};

	//控制模态框显示
	handleOpenOrClose = () => {
		this.setState({
			showReportModal: !this.state.showReportModal
		});
	};

	//全选
	onAllCheckChange = () => {
		let self = this;
		let checkedArray = [];
		for (var i = 0; i < self.state.checkedArray.length; i++) {
			checkedArray[i] = !self.state.checkedAll;
		}
		self.setState(
			{
				checkedAll: !self.state.checkedAll,
				checkedArray: checkedArray
			},
			() => {
				this.controlButton();
			}
		);
	};
	//checkbox改变事件
	onCheckboxChange = (text, record, index) => {
		let self = this;
		let allFlag = false;
		let checkedArray = self.state.checkedArray.concat();
		checkedArray[index] = !self.state.checkedArray[index];
		for (var i = 0; i < self.state.checkedArray.length; i++) {
			if (!checkedArray[i]) {
				allFlag = false;
				break;
			} else {
				allFlag = true;
			}
		}
		self.setState(
			{
				checkedAll: allFlag,
				checkedArray: checkedArray
			},
			() => {
				this.controlButton();
			}
		);
	};

	//给表格每一列加checkbox
	renderColumnsMultiSelect(columns) {
		const { checkedArray } = this.state;
		const { multiSelect } = this.props;
		let indeterminate_bool = false;
		if (multiSelect && multiSelect.type === 'checkbox') {
			let i = checkedArray.length;
			while (i--) {
				if (checkedArray[i]) {
					indeterminate_bool = true;
					break;
				}
			}
			let defaultColumns = [
				{
					title: (
						<NCCheckbox
							className="table-checkbox"
							checked={this.state.checkedAll}
							indeterminate={indeterminate_bool && !this.state.checkedAll}
							onChange={this.onAllCheckChange}
						/>
					),
					key: 'checkbox',
					dataIndex: 'checkbox',
					width: '50px',
					render: (text, record, index) => {
						return (<div fieldid="checkbox" >
							<NCCheckbox
								className="table-checkbox"
								checked={this.state.checkedArray[index]}
								onChange={this.onCheckboxChange.bind(this, text, record, index)}
							/>
						</div>);
					}
				}
			];
			columns = defaultColumns.concat(columns);
		}
		return columns;
	}

	render() {
		let { nccCloseAccountVOs, showReportModal, checkedDatas, reportTableData } = this.state;
		let { button, title } = this.props;
		let { createButtonApp } = button;
		const { createBillHeadInfo } = this.props.BillHeadInfo;
		return (
			<div className="nc-bill-list batch-close-account">
				<NCDiv areaCode={NCDiv.config.HEADER} className="nc-bill-header-area">
					<div className="header-title-search-area">
						{createBillHeadInfo({
							title: title,
							initShowBackBtn: false
						})}
					</div>
					<div className="header-button-area">
						{createButtonApp({
							area: 'list_head',
							buttonLimit: 3,
							onButtonClick: buttonClick.bind(this),
							popContainer: document.querySelector('.header-button-area')
						})}
					</div>
				</NCDiv>
				<div className="nc-bill-search-area nc-theme-form-label-c">
					{/* //表头 */}
					{this.getHeadData()}
				</div>
				<NCDiv fieldid="ncc" areaCode={NCDiv.config.TABLE} className="nc-bill-table-area batchcloseaccount"> 
					{/* //表体 */}
					<NCTable
						columns={this.renderColumnsMultiSelect(this.Defaultcolumns)}
						bordered
						isDrag
						data={nccCloseAccountVOs}
						scroll={{
							x:
								this.Defaultcolumns.length > 8
									? 100 + (this.Defaultcolumns.length - 8) * 15 + '%'
									: '100%',
							y: 569
						}}
						bodyStyle={{height:getTableHeight(130)}}
						scroll={{ x: true, y: getTableHeight(130) }}
					/>
				</NCDiv>
				<ReportModal
					showReportModal={showReportModal}
					handleOpenOrClose={this.handleOpenOrClose}
					checkedDatas={checkedDatas}
					reportTableData={reportTableData}
					batchCloseAccount={this.batchCloseAccount}
				/>
			</div>
		);
	}
}
BatchCloseAccount.defaultProps = defaultProps12;

BatchCloseAccount = createPage({
	initTemplate: initTemplate
})(BatchCloseAccount);

export default function (props = {}) {
	var conf = {};

	return <BatchCloseAccount {...Object.assign(conf, props)} />;
}
